package com.schoolegard.services.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.schoolegard.services.MessageStrategyService;
import com.schoolgard.dao.MessageStrategyDao;
import com.schoolgard.entitybean.GridDataModel;
import com.schoolgard.entitybean.MessageStrategy;

public class MessageStrategyServiceImpl implements MessageStrategyService {

	private MessageStrategyDao messageStrategyDao;

	public void setMessageStrategyDao(MessageStrategyDao messageStrategyDao) {
		this.messageStrategyDao = messageStrategyDao;
	}

	@Override
	public void save(MessageStrategy ms) {
		messageStrategyDao.createOrModify(ms);
	}

	@Override
	public void delete(Long id) {
		messageStrategyDao.remove(findById(id));
	}

	@Override
	public MessageStrategy findOne(MessageStrategy ms) {
		DetachedCriteria criteria = DetachedCriteria.forClass(MessageStrategy.class);
		if (ms == null) {
			return null;
		}
		if (ms.getAlarmLevel() != null) {
			criteria.add(Restrictions.eq("alarmLevel", ms.getAlarmLevel()));
		}
		if (ms.getAlarmTimes() != null) {
			criteria.add(Restrictions.eq("alarmTimes", ms.getAlarmTimes()));
		}
		if (ms.getAlarmTypeId() != null) {
			criteria.add(Restrictions.eq("alarmTypeId", ms.getAlarmTypeId()));
		}
		List<MessageStrategy> msList = messageStrategyDao.findByCriteria(criteria);
		if (msList != null && msList.size() > 0) {
			return msList.get(0);
		}
		return null;
	}

	@Override
	public GridDataModel<MessageStrategy> find4Page(MessageStrategy ms, int first, int max) {
		DetachedCriteria criteria = DetachedCriteria.forClass(MessageStrategy.class);
		if (ms != null) {
			if (ms.getAlarmLevel() != null) {
				criteria.add(Restrictions.eq("alarmLevel", ms.getAlarmLevel()));
			}
			if (ms.getAlarmTimes() != null) {
				criteria.add(Restrictions.eq("alarmTimes", ms.getAlarmTimes()));
			}
			if (ms.getAlarmTypeId() != null) {
				criteria.add(Restrictions.eq("alarmTypeId", ms.getAlarmTypeId()));
			}
		}
		criteria.addOrder(Order.asc("alarmLevel"));
		criteria.addOrder(Order.asc("alarmTypeId"));
		try {
			List<MessageStrategy> logs = messageStrategyDao.findByCriteria(criteria, first, max);
			int total = messageStrategyDao.getRowCount(criteria);
			GridDataModel<MessageStrategy> page = new GridDataModel<MessageStrategy>();
			page.setPage(first / max + 1);
			page.setRows(logs);
			page.setTotal(total);
			return page;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public MessageStrategy findById(Long id) {
		return messageStrategyDao.findById(id);
	}

}
